//
//  GGFaceIdManManage.m
//  ToolsDemo
//
//  Created by IOS on 2021/6/30.
//

#import "GGFaceIdManManage.h"
#include <sys/sysctl.h>

#define kCanFaceIdKey @"IsHasBing_Biometric"
#define kBiometricFirstKey @"BiometricFirstLogin"

@implementation GGFaceIdManManage

+ (GGFaceIdManManage *)shareManage
{
    static GGFaceIdManManage *man = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        man = [[GGFaceIdManManage alloc] init];
    });
    return man;
}

+ (BOOL)gg_isFirst {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kBiometricFirstKey]) {
        return [[NSUserDefaults standardUserDefaults] boolForKey:kBiometricFirstKey];
    }
    return NO;
}

+ (void)gg_setFirst {
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kBiometricFirstKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

+ (void)gg_saveData {
    
//    UserLoginModel *loginModel = [UserLoginModel modelFromLocal];
//
//    NSLog(@"-----\n phone = %@-%@ \n google = %@ \n fb = %@ \n apple = %@ \n-----",loginModel.code,loginModel.phone,loginModel.google,loginModel.facebook,loginModel.apple);
    // 优先缓存手机号
    NSString *typeStr = @"phone";
    NSString *account = @"";
    NSString *pCode = [NSString stringWithFormat:@"%ld",USERManager.userModel.code];
    NSString *tokenStr = [[BRUserManager share] token];
    if (USERManager.userModel.phone.length != 0) {
        account = [NSString stringWithFormat:@"%ld-%@",USERManager.userModel.code,USERManager.userModel.phone];
    }else {
        account = USERManager.userModel.email;
    }
    NSDictionary *dic = @{@"typeStr":typeStr,@"account":account,@"pCode":pCode,@"tokenStr":tokenStr};
    NSString *jsonStr = [dic mj_JSONString];
    [[NSUserDefaults standardUserDefaults] setObject:jsonStr forKey:kCanFaceIdKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

+ (BOOL)gg_checkIsEqual {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:kCanFaceIdKey]) {
        
        GGBiometricModel *oldModel = [self gg_model];
        NSString *account = @"";
        if (USERManager.userModel.phone.length != 0) {
            account = [NSString stringWithFormat:@"%ld-%@",USERManager.userModel.code,USERManager.userModel.phone];
        }else {
            account = USERManager.userModel.email;
        }
        if ([oldModel.account isEqualToString:account]) {
            return YES;
        }
    }
    
    return NO;
}

+ (void)gg_removeCache {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCanFaceIdKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (GGBiometricModel *)gg_model {

    if ([[NSUserDefaults standardUserDefaults] objectForKey:kCanFaceIdKey]) {
        NSString *jsonStr = [[NSUserDefaults standardUserDefaults] objectForKey:kCanFaceIdKey];
        NSDictionary *dic = [jsonStr mj_JSONObject];
        if (BR_DictIsEmpty(dic)) {
            return [GGBiometricModel new];
        }
        GGBiometricModel *model = [GGBiometricModel mj_objectWithKeyValues:[jsonStr mj_JSONObject]];
        return model;
    }
    return [GGBiometricModel new];

}

+ (NSString *)gg_token {
    
    GGBiometricModel *model = [GGFaceIdManManage gg_model];
    
    return model.tokenStr;
}


+ (BOOL)gg_showBtn {
    
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) return NO;
    //    老设备忽略
    if (![self gg_isSuportBiometrics]) return NO;
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:kCanFaceIdKey])  return NO;
    
    return YES;
//    NSString *keyStr = [[NSUserDefaults standardUserDefaults] objectForKey:kCanFaceIdKey];
//    if (keyStr.length > 0) return YES;
//
//    return NO;
}

+ (BOOL)gg_isSuportBiometrics {
    // 如果设备没有生物识别功能
    if ([self gg_platformType] == 0) {
        return NO;
    }
    return YES;
}

+ (NSString *)gg_getSuportTypeStr {
    NSInteger type = [self gg_platformType];
    if (type == 1) {
        return @"Touch ID";
    }
    if (type == 2) {
        return @"Face ID";
    }
    return @"Suport off";
}

+ (void)gg_checkFaceAction:(void(^)(void))succ faile:(void(^)(NSInteger code))faile {
    
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        succ();
        
    }else {
        
        faile(error.code);
       
    }
}

+ (void)gg_runFaceAction:(void(^)(void))succ faile:(void(^)(NSInteger code))faile {
    
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        context.localizedFallbackTitle = @"";
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:Localized(@"Set_toLogin") reply:^(BOOL success, NSError * _Nullable error) {
                    
            if (success) {
                NSLog(@"生物识别验证成功");
                succ();
                
            }else {
                NSLog(@"验证失败：%@ \n",error.description);
                faile(error.code);
            }
            
        }];
        
    }else {
        // -2 取消  -6 关闭权限
        
        NSString *tagerStr  = [self gg_getSuportTypeStr];
        NSString *conten = @"";
        if (error.code == LAErrorPasscodeNotSet) {
            // 密码未设置
            NSLog(@"密码未设置");
            conten = [NSString stringWithFormat:Localized(@"Set_Biometry_NotSet"),tagerStr,tagerStr,tagerStr];
//            [HUD showHUDWithText:conten];
        }else {
            // Fallback on earlier versions
            if (@available(iOS 11.0, *)) {
                if (error.code == LAErrorBiometryLockout) {
                    // 被锁定
                    NSLog(@"被锁定");
//                    conten = @"多次错误被锁定";
                }else if (error.code == LAErrorBiometryNotAvailable) {
                    // 未打开 只有faceId可以关闭 touchID 无关闭权限功能
                    NSLog(@" 未打开");
                    conten = [NSString stringWithFormat:Localized(@"Set_Biometry_Off"),tagerStr,tagerStr];
                } else if (error.code == LAErrorBiometryNotEnrolled) {
                    // 未录入
                    conten = [NSString stringWithFormat:Localized(@"Set_Biometry_NotSet"),tagerStr,tagerStr,tagerStr];
                }
            }
        }
        if (conten.length != 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [BRHud showAuto:conten];
            });
        }
        
        NSLog(@"%@ - (%ld)",conten,error.code);
        
        faile(error.code);
    }
}



+ (NSString *)gg_platform{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithUTF8String:machine];
    free(machine);
    return platform;
}

+ (NSInteger)gg_platformType{
    NSString *platform = [self gg_platform];
    
    // iphone 8 以下带指纹的手机 se2 se
    if ([platform isEqualToString:@"iPhone6,1"] ||
        [platform isEqualToString:@"iPhone6,2"] ||
        [platform isEqualToString:@"iPhone7,1"] ||
        [platform isEqualToString:@"iPhone7,2"] ||
        [platform isEqualToString:@"iPhone8,1"] ||
        [platform isEqualToString:@"iPhone8,2"] ||
        [platform isEqualToString:@"iPhone8,4"] ||
        [platform isEqualToString:@"iPhone9,1"] ||
        [platform isEqualToString:@"iPhone9,2"] ||
        [platform isEqualToString:@"iPhone9,3"] ||
        [platform isEqualToString:@"iPhone9,4"] ||
        [platform isEqualToString:@"iPhone10,1"] ||
        [platform isEqualToString:@"iPhone10,4"] ||
        [platform isEqualToString:@"iPhone10,2"] ||
        [platform isEqualToString:@"iPhone12,8"]
        )    return 1;
    
    // 其他设备
    if ([platform isEqualToString:@"iPhone1,1"] ||
        [platform isEqualToString:@"iPhone1,2"] ||
        [platform isEqualToString:@"iPhone2,1"] ||
        [platform isEqualToString:@"iPhone3,1"] ||
        [platform isEqualToString:@"iPhone3,3"] ||
        [platform isEqualToString:@"iPhone4,1"] ||
        [platform isEqualToString:@"iPhone5,1"] ||
        [platform isEqualToString:@"iPhone5,2"] ||
        [platform isEqualToString:@"iPhone5,3"] ||
        [platform isEqualToString:@"iPhone5,4"]
        ) return 0;
    
    // iphone x以上带faceID的手机（目前到12）
    return 2;
//    if ([platform isEqualToString:@"iPhone10,3"] ||
//        [platform isEqualToString:@"iPhone10,6"] ||
//        [platform isEqualToString:@"iPhone11,2"] ||
//        [platform isEqualToString:@"iPhone11,4"] ||
//        [platform isEqualToString:@"iPhone11,6"] ||
//        [platform isEqualToString:@"iPhone11,8"] ||
//        [platform isEqualToString:@"iPhone12,1"] ||
//        [platform isEqualToString:@"iPhone12,3"] ||
//        [platform isEqualToString:@"iPhone12,5"] ||
//        [platform isEqualToString:@"iPhone12,8"] ||
//        [platform isEqualToString:@"iPhone13,1"] ||
//        [platform isEqualToString:@"iPhone13,2"] ||
//        [platform isEqualToString:@"iPhone13,3"] ||
//        [platform isEqualToString:@"iPhone13,4"]
//        )   return 2;
}

@end
